var CONFIG = require('../config');
var redis = require('redis');
var client = redis.createClient(CONFIG.RDS_PORT, CONFIG.RDS_HOST, CONFIG.RDS_OPTS);

var db = {};

client.auth(CONFIG.RDS_PWD, function() {
    console.log('认证通过');
});

client.on('error', function(err) {
    console.log('Error : ', err);
});

client.on('connect', function() {
    client.select(CONFIG.TokenRedisDb, function(e, d) {
        if(e) return console.log(e);
        if(d == 'OK') return console.log('DB['+ CONFIG.TokenRedisDb +'] Redis连接成功！');
    });
});

client.on('end', function() {
    console.log('end');
});

db.set = function(key, value, expire, callback) {
    client.set(key, value, function(err, result) {
        if(err) return callback(err,null);
        if(!isNaN(expire) && expire > 0) client.expire(key, parseInt(expire));
        callback(null, result);
    });
}

db.get = function (key, callback) {
    client.get(key, function (err, result) {
        if(err) return callback(err, null);
        callback(null, result);
    });
}

db.expire = function(key, time, callback){
    client.expire(key, time, function(err, result){
        if(err) return callback(err, null);
        callback(null, result);
    })
}

db.del = function(key, callback) {
    client.del(key , function(err, result){
        if(err) return callback(err, null);
        callback(null, result);
    });
}

db.select = function(db, callback) {
    client.select(db, function(e, result){
        if(e) return callback(e, null);
        callback(null, result);
    })
}

module.exports = db;